package shujia.day09;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/*
    存储自定义对象并遍历 Student(name,age)

    1、创建集合对象
    2、创建元素对象
    3、将元素添加到集合中
    4、遍历集合
 */
public class CollectionDemo5 {
    public static void main(String[] args) {
        Collection c1 = new ArrayList();

        Student s1 = new Student("张三", 18);
        Student s2 = new Student("李四", 17);
        Student s3 = new Student("王五", 18);
        Student s4 = new Student("赵六", 19);

        c1.add(s1);
        c1.add(s2);
        c1.add(s3);
        c1.add(s4);

        //方式1：转数组遍历
        Object[] array = c1.toArray();
        for (int i = 0; i < array.length; i++) {
            Object o = array[i]; // new Student("张三", 18);
            Student s = (Student) o;
            System.out.println(s.getName() + "-" + s.getAge());
        }

        System.out.println("-----------------------");
        //方式2：使用迭代器的方式遍历
        Iterator iterator = c1.iterator();
        while (iterator.hasNext()){
            Object o = iterator.next();// new Student("张三", 18);
            Student s = (Student) o;
            System.out.println(s.getName() + "-" + s.getAge());
        }


    }
}
